package com.only4play.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;


import java.util.Objects;

/**
 * @author liyuncong
 * @version 1.0
 * @file CookieUtils
 * @brief Cookie工具类
 * @details Cookie工具类
 * @date 2023-11-19
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-19               liyuncong          Created
 */
public class CookieUtils {

    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isEmpty(cookies) || StringUtils.isBlank(name)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (Objects.equals(name, cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    public static void addCookie(
        String name, String value, String path, HttpServletRequest request, HttpServletResponse response
    ) {
        Cookie cookie = new Cookie(name, value);
        if (StringUtils.isNotBlank(path)) {
            cookie.setPath(path);
        }
        if (Objects.equals("Https", request.getScheme())) {
            cookie.setSecure(true);
        }
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
